<?php
    class comm_model extends Model
    {
        //no database usage model
        public function __construct(){
            parent::__construct();
        }
        
        public function genJSON($value){
            return json_encode($value);
        }
        
        public function genXML($tag, $val, $tight = false, $recur = false){
            $header =  is_integer($recur) ? '' : "<?xml version='1.0' standalone='yes'?>";
            
            $code = $recur ? $val : json_decode(json_encode($val));

            $recur = intval($recur);
            $indent = (0 === $recur || $tight) ? '' : str_repeat("\t", $recur - 1);

            //validate tag for rfc
            //TODO validate tag
            
            $ret = $tight || empty($header) ? "$header" : "$header\n";
            if ($code instanceof stdClass){
                $ret .= $indent;
                $ret .= $tight ? "<$tag>" : "<$tag>\n";
                foreach($code as $key => &$value){
                    $ret .= $this->genXML($key, $value, $tight, $recur + 1);
                }
                $ret .= $indent;
                $ret .= $tight ? "</$tag>" : "</$tag>\n";
            }
            else{
                if (is_array($code))
                    foreach($code as &$value){
                        $ret .= $this->genXML($tag, $value, $tight, $recur);
                    }
                else{
                    $ret .= "$indent<$tag>$code</$tag>";
                    $ret .= $tight ? "" : "\n";
                }
            }
            return $ret;
        }
        
        public function readJSON($jsonString){
            return (array)json_decode($jsonString);
        }
        
        public function readXML($xml){
            return new SimpleXMLElement($xml);
        }
    }